// Learn more about Tauri commands at https://tauri.app/develop/calling-rust/

use tauri::{Manager, Runtime, WebviewUrl, WebviewWindowBuilder, WindowEvent, Result};

// 显示主窗口并隐藏悬浮球窗口的命令
#[tauri::command]
async fn show_main_window_and_hide_floating_ball<R: Runtime>(app: tauri::AppHandle<R>) -> Result<()> {
    if let Some(main_window) = app.get_webview_window("main-window") {
        main_window.show()?;
        main_window.unminimize()?;
        main_window.set_focus()?;
    }

    if let Some(floating_ball_window) = app.get_webview_window("floating-ball") {
        floating_ball_window.hide()?;
    }
    Ok(())
}

// 显示悬浮球窗口的命令
#[tauri::command]
async fn show_floating_ball<R: Runtime>(app: tauri::AppHandle<R>) -> Result<()> {
    if let Some(floating_ball_window) = app.get_webview_window("floating-ball") {
        floating_ball_window.show()?;
    }
    Ok(())
}

// 隐藏悬浮球窗口的命令
#[tauri::command]
async fn hide_floating_ball<R: Runtime>(app: tauri::AppHandle<R>) -> Result<()> {
    if let Some(floating_ball_window) = app.get_webview_window("floating-ball") {
        floating_ball_window.hide()?;
    }
    Ok(())
}

#[cfg_attr(mobile, tauri::mobile_entry_point)]
pub fn run() {
    tauri::Builder::default()
        .setup(|app| {
            // 获取主窗口引用
            let main_window = app.get_webview_window("main-window")
                .expect("Main window should be created during app initialization");

                // 获取主窗口位置和尺寸
            // 创建或获取悬浮球窗口
            let floating_ball_window = match app.get_webview_window("floating-ball") {
                Some(window) => window,
                None => {
                    let window = WebviewWindowBuilder::new(
                        app,
                        "floating-ball",
                        WebviewUrl::App("/floating-ball".into()),
                    )
                    .transparent(true)
                    .decorations(false)
                    .resizable(false)
                    .always_on_top(true)
                    .inner_size(64.0, 64.0)
                    .center()
                    .shadow(false)
                    .drag_and_drop(true)
                    .skip_taskbar(true)
                    .build()?;
                    window.hide()?;
                    window
                }
            };

            // 克隆窗口引用用于事件处理
            let floating_ball_window_clone = floating_ball_window.clone();
            
            // 设置主窗口事件处理器
            main_window.on_window_event(move |event| {
                // 生产环境中可以移除或替换为适当的日志级别
                #[cfg(debug_assertions)]
                println!("Main window event: {:?}", event);
                
                match event {
                    WindowEvent::Resized(size) => {
                        // 根据窗口尺寸判断是否最小化
                        if size.width == 0 && size.height == 0 {
                            // 窗口最小化时显示悬浮球
                            if let Err(e) = floating_ball_window_clone.show() {
                                eprintln!("Failed to show floating ball on minimize: {:?}", e);
                            }
                        }else{
                            // 窗口最大化时隐藏悬浮球
                            if let Err(e) = floating_ball_window_clone.hide() {
                                eprintln!("Failed to hide floating ball on maximize: {:?}", e);
                            }
                        }
                    }
                    WindowEvent::Focused(is_focused) => {
                      
                        
                        #[cfg(debug_assertions)]
                        if !*is_focused {
                             if let Err(e) = floating_ball_window_clone.show() {
                                eprintln!("Failed to show floating ball on minimize: {:?}", e);
                            }
                        }
                    }
                    // 主窗口销毁时销毁悬浮球窗口
                    WindowEvent::Destroyed => {
                        if let Err(e) = floating_ball_window_clone.destroy() {
                            eprintln!("Failed to destroy floating ball window: {:?}", e);
                        }
                    }
                    _ => {} // 处理其他所有事件
                }
            });
            
            Ok(())
        })
        .plugin(tauri_plugin_opener::init())
        .invoke_handler(tauri::generate_handler![
            show_main_window_and_hide_floating_ball,
            show_floating_ball,
            hide_floating_ball
        ])
        .run(tauri::generate_context!())
        .expect("error while running tauri application");
}
